package net.fornwall.eclipsecoder.rubysupport;

import java.io.ByteArrayInputStream;

import net.fornwall.eclipsecoder.languages.LanguageSupport;
import net.fornwall.eclipsecoder.stats.CodeGenerator;
import net.fornwall.eclipsecoder.stats.ProblemStatement;
import net.fornwall.eclipsecoder.util.Utilities;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.rubypeople.rdt.core.RubyCore;
import org.rubypeople.rdt.internal.launching.RubyRuntime;
import org.rubypeople.rdt.ui.IRubyConstants;

public class RubyLanguageSupport extends LanguageSupport {

    public static final String LANGUAGE_NAME = "Ruby";

    @Override
    protected CodeGenerator createCodeGenerator(ProblemStatement problemStatemnt) {
        return new RubyCodeGenerator(problemStatemnt);
    }

    @Override
    protected IFile createLanguageProject(IProject project) throws Exception {
        RubyCore.addRubyNature(project, null);

        IFile testsFile = project.getFile(getProblemStatement().getSolutionClassName() + "Test.rb");
        testsFile.create(new ByteArrayInputStream(getCodeGenerator().getTestsSource().getBytes()),
                true, null);

        IFile sourceFile = project.getFile(getSolutionFileName());
        sourceFile.create(new ByteArrayInputStream(getInitialSource().getBytes()), true, null);

        if (RubyRuntime.getDefault().getSelectedInterpreter() == null) {
            Utilities.showMessageDialog("Cannot launch TestUnit test",
                    "No Ruby interpreter has been selected");
        } else {
            try {
                RubyTestLauncher launcher = new RubyTestLauncher(testsFile);
                launcher.run();
            } catch (Exception e) {
                Utilities.showException(e);
            }
        }

        return sourceFile;
    }

    @Override
    protected String getCodeEditorID() {
        return IRubyConstants.EDITOR_ID;
    }

    @Override
    protected String getCodeTemplate() {
        return "class $CLASSNAME$\n\tdef $METHODNAME$($METHODPARAMS$)\n\t\treturn $DUMMYRETURN$\n\tend\nend\n";
    }

    @Override
    public String getLanguageName() {
        return LANGUAGE_NAME;
    }

    @Override
    public String getPerspectiveID() {
        return "org.rubypeople.rdt.ui.PerspectiveRuby";
    }

    @Override
    protected String getSolutionFileName() {
        return getProblemStatement().getSolutionClassName() + ".rb";
    }

    @Override
    protected String getSubmission() throws Exception {
        return null;
    }
}
